package com.cmeduSystem.common.flow.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.cmeduSystem.common.core.util.ApplicationContextHolder;
import com.cmeduSystem.common.flow.constant.FlowConstant;
import com.cmeduSystem.common.flow.object.FlowBusinessOperationConfig;
import com.cmeduSystem.common.flow.service.FlowTaskExtService;
import com.cmeduSystem.common.flow.util.FlowBusinessHelper;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 流程任务开始监听器，主要用于流程提交后和业务表数据的交互。
 *
 * @author xulei
 * @date 2025-09-04
 */
@Slf4j
public class FlowTaskBusinessOperationStartListener implements TaskListener {

    private final transient FlowTaskExtService flowTaskExtService =
            ApplicationContextHolder.getBean(FlowTaskExtService.class);
    private final transient FlowBusinessHelper flowBusinessHelper =
            ApplicationContextHolder.getBean(FlowBusinessHelper.class);

    @Override
    public void notify(DelegateTask d) {
        List<FlowBusinessOperationConfig> configs =
                flowTaskExtService.parseFlowBusinessOperationConfig(d.getProcessDefinitionId(), d.getTaskDefinitionKey());
        configs = configs.stream()
                .filter(c -> StrUtil.equals(c.getOperationType(), FlowConstant.EVENT_TYPE_ENTER_TASK))
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(configs)) {
            return;
        }
        JSONObject variableData = flowBusinessHelper.getNonRealtimeSystemVariables();
        variableData.putAll(d.getVariables());
        for (FlowBusinessOperationConfig config : configs) {
            flowBusinessHelper.executeBusinessOperation(config, d.getExecutionId(), d.getTaskDefinitionKey(), variableData);
        }
    }
}
